package com.daxidi.cn.controller;


import com.alibaba.fastjson.JSON;
import com.daxidi.cn.annotation.LogAnnotation;
import com.daxidi.cn.config.wxconfig.WxPayConfig;
import com.daxidi.cn.cons.ShgCons;
import com.daxidi.cn.entity.Bill;
import com.daxidi.cn.entity.Clerk;
import com.daxidi.cn.entity.Shop;
import com.daxidi.cn.entity.User;
import com.daxidi.cn.enums.LogTypeEnum;
import com.daxidi.cn.mapper.BillMapper;
import com.daxidi.cn.params.AddBillParam;
import com.daxidi.cn.params.AddItemBillParam;
import com.daxidi.cn.params.MemberAddBillParam;
import com.daxidi.cn.service.*;
import com.daxidi.cn.utils.MD5Utils;
import com.daxidi.cn.utils.ReturnResult;
import com.daxidi.cn.utils.ReturnResultUtils;
import com.daxidi.cn.vo.AddItemBillVo;
import com.daxidi.cn.vo.MemberBillVo;
import com.github.wxpay.sdk.WXPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 订单表 order 系统默认字段不能用 前端控制器
 * </p>
 *
 * @author wsh
 * @since 2020-11-09
 */
@Log4j
@Api(tags = "订单模块接口")
@RestController
@RequestMapping("/api/v1/union/bill")
public class BillController {

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private WxPayConfig wxPayConfig;

    @Autowired
    private IBillService billService;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private IShopService shopService;

    @Autowired
    private BillMapper billMapper;

    @Autowired
    private IClerkService clerkService;

    @Autowired
    private IUserService userService;

    @LogAnnotation(content = "扫码枪订单添加", type = LogTypeEnum.ADD)
    @ApiOperation(value = "订单  扫码枪订单添加接口")
    @ApiResponses({
            @ApiResponse(code = 20000, message = "添加成功"),
            @ApiResponse(code = 20001, message = "添加失败"),
            @ApiResponse(code = 20401, message = "认证失败"),
            @ApiResponse(code = 20402, message = "时间戳过期"),
            @ApiResponse(code = 20403, message = "商家已经注销"),
            @ApiResponse(code = 20404, message = "商家不存在"),
            @ApiResponse(code = 20405, message = "折扣优惠率不正确"),
            @ApiResponse(code = 20406, message = "商家未上传子商户ID"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PostMapping("/itemBill")
    public ReturnResult addItemBill(@RequestBody AddItemBillParam addItemBillParam){
        String pwd = addItemBillParam.getShopId() + ":" + addItemBillParam.getNonce() + ":" + ShgCons.SECRET_KEY;
        if (!MD5Utils.MD5Encode(pwd).equals(addItemBillParam.getSign())){
            return ReturnResultUtils.returnFailMsg(20401, "认证失败！");
        }
        if (System.currentTimeMillis() - addItemBillParam.getTimestamp().getTime() > 600000){
            return ReturnResultUtils.returnFailMsg(20402, "时间戳过期！");
        }
        if (ObjectUtils.isEmpty(shopService.selectShop(addItemBillParam.getShopId()))){
            return ReturnResultUtils.returnFailMsg(20404, "商家不存在！");
        }
        if (shopService.selectShop(addItemBillParam.getShopId()).getEnable() != 1){
            return ReturnResultUtils.returnFailMsg(20403, "商家已经注销！");
        }
        if (null == shopService.selectShop(addItemBillParam.getShopId()).getSubMchId()){
            return ReturnResultUtils.returnFailMsg(20406, "商家未上传子商户ID！");
        }
        if (Double.valueOf(shopService.selectShop(addItemBillParam.getShopId()).getDiscount()) != addItemBillParam.getDiscount()){
            return ReturnResultUtils.returnFailMsg(20405, "折扣优惠率不正确！");
        }
        try {
            //添加订单
            Bill bill = new Bill();
            BeanUtils.copyProperties(addItemBillParam, bill);
            bill.setCreatedAt(new Date());
            bill.setFree(addItemBillParam.getTotal() - addItemBillParam.getDiscounted());
            //订单状态，默认未支付
            bill.setState(0);
            //来源 2.商家调用
            bill.setSource(2);
            //回调地址
            if (null == addItemBillParam.getCallBack()){
                addItemBillParam.setCallBack(wxPayConfig.getNotifyUrls());
            }
            bill.setNotifyUrl(addItemBillParam.getCallBack());
            billService.addBill(bill);
            AddItemBillVo addItemBillVo = new AddItemBillVo();
            BeanUtils.copyProperties(bill, addItemBillVo);
            String addItemBillStr = JSON.toJSONString(addItemBillVo);
            WebSocketServer.sendInfo(addItemBillStr, addItemBillVo.getMembeId().toString());
            return ReturnResultUtils.returnSuccess(addItemBillVo);
        } catch (Exception e){
            log.error("扫码枪订单添加失败！" + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(20001, "扫码枪订单添加失败！");
        }
    }

    @LogAnnotation(content = "微信扫码订单添加", type = LogTypeEnum.ADD)
    @ApiOperation(value = "订单  微信扫码订单添加接口")
    @ApiResponses({
            @ApiResponse(code = 116, message = "添加成功"),
            @ApiResponse(code = 117, message = "添加失败"),
            @ApiResponse(code = 317, message = "商家未开通收费通道，请联系管理员"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PostMapping("/")
    public ReturnResult addBill(@RequestBody AddBillParam addBillParam) {
        try {
            //根据shopId查询shop表判断子商户id是否为空
            Shop shop = shopService.selectShop(addBillParam.getShopId());
            if (null == shop.getSubMchId()) {
                return ReturnResultUtils.returnFailMsg(317, "商家未开通收费通道，请联系管理员");
            }

            Bill bill = new Bill();
            BeanUtils.copyProperties(addBillParam, bill);
            bill.setCreatedAt(new Date());
            //订单Id
            bill.setOrderId(System.currentTimeMillis() + Long.valueOf(String.format("%04d", addBillParam.getMembeId())) + addBillParam.getShopId());
            //订单状态
            bill.setState(0);
            //来源 1.小程序
            bill.setSource(1);
            billService.addBill(bill);
            MemberBillVo memberBillVo = new MemberBillVo();
            BeanUtils.copyProperties(bill, memberBillVo);
            //商家名称
            memberBillVo.setShopName(shop.getName());
            String billStr = JSON.toJSONString(memberBillVo);
            webSocketServer.sendInfo(billStr, addBillParam.getMembeId().toString());
            return ReturnResultUtils.returnSuccess(memberBillVo);
        } catch (Exception e) {
            log.error("添加失败" + e);
            return ReturnResultUtils.returnFailMsg(117, "添加失败");
        }
    }

    @LogAnnotation(content = "微信扫码直接支付生成订单", type = LogTypeEnum.ADD)
    @ApiOperation(value = "订单  微信扫码订单添加接口 直接支付")
    @ApiResponses({
            @ApiResponse(code = 116, message = "添加成功"),
            @ApiResponse(code = 117, message = "添加失败"),
            @ApiResponse(code = 317, message = "商家未开通收费通道，请联系管理员"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PostMapping("/memberBill")
    public ReturnResult memberAddBill(@RequestBody MemberAddBillParam addBillParam) {
        try {
            //根据shopId查询shop表判断子商户id是否为空
            Shop shop = shopService.selectShop(addBillParam.getShopId());
            if (null == shop.getSubMchId()) {
                return ReturnResultUtils.returnFailMsg(317, "商家未开通收费通道，请联系管理员");
            }

            Bill bill = new Bill();
            BeanUtils.copyProperties(addBillParam, bill);
            bill.setCreatedAt(new Date());
            //订单Id
            bill.setOrderId(System.currentTimeMillis() + Long.valueOf(String.format("%04d", addBillParam.getMembeId())) + addBillParam.getShopId());
            //订单状态
            bill.setState(0);
            //来源 1.小程序
            bill.setSource(1);
            Double free = (double) Math.round(addBillParam.getFree() * 100) / 100;
            bill.setFree(free);
            billService.addBill(bill);
            MemberBillVo memberBillVo = new MemberBillVo();
            BeanUtils.copyProperties(bill, memberBillVo);
            //商家名称
            memberBillVo.setShopName(shop.getName());
            String billStr = JSON.toJSONString(memberBillVo);

            try {
                //根据orderId获取bill对象
                log.info("===1.===根据orderId获取bill对象===");
                //Bill bill = billService.selectBillByOrderId(Long.valueOf(orderId));
                //更新payAt时间
                bill.setPayAt(new Date());
                billMapper.updateById(bill);
                String discounted = bill.getDiscounted() + "";
                Double fee = Double.valueOf(discounted);
                fee = (double) Math.round(fee * 100) / 100;

                Integer totalFee = Integer.parseInt(new java.text.DecimalFormat("0").format(fee * 100));
                //根据clerkId获取shopId，获取shopName
                log.info("===2.===根据clerkId获取shopId，获取shopName===");
                Clerk clerk = clerkService.selectClerkById(bill.getClerkId());
                log.info("===3.===开始查询商铺===");
                //Shop shop = shopService.selectShop(clerk.getShopId());
                String payBody = "工会会员支付";
                //根据memberId获取openId
                log.info("===4.===根据memberId获取openId===");
                User user = userService.selectUserByMemberId(bill.getMembeId());
                String openId = user.getOpenId();
                log.info("===5.===开始支付===");
                //获取微信支付mapResult
                Map<String, String> mapResult = wxPayService.unifiedOrderJs(totalFee, payBody, bill.getOrderId()+"", openId);
                log.info("===返回微信支付成功！===" + mapResult);

                //以下内容是返回前端页面的json数据
                String prepay_id = "";//预支付id
                if ("SUCCESS".equals(mapResult.get("return_code")) && "SUCCESS".equals(mapResult.get("result_code"))) {
                    prepay_id = mapResult.get("prepay_id");
                }
                Map<String, String> payMap = new HashMap<String, String>();
                payMap.put("appId", "wx19b5a41593f4211b");
                payMap.put("nonceStr", WXPayUtil.generateNonceStr());
                payMap.put("package", "prepay_id=" + prepay_id);
                payMap.put("signType", "MD5");
                payMap.put("timeStamp", System.currentTimeMillis()+"");

                String paySign = WXPayUtil.generateSignature(payMap, wxPayConfig.getKey());
                payMap.put("paySign", paySign);
                payMap.put("memberBillVo", billStr);
                return ReturnResultUtils.returnSuccess(payMap);
            } catch (Exception e) {
                log.error("===返回微信支付失败！===" + e);
                e.printStackTrace();
                return ReturnResultUtils.returnFailMsg(415, "支付失败！" + e);
            }
        } catch (Exception e) {
            log.error("添加失败" + e);
            return ReturnResultUtils.returnFailMsg(117, "添加失败");
        }
    }

    @ApiOperation(value = "订单  获取会员订单接口")
    @ApiResponses({
            @ApiResponse(code = 116, message = "添加成功"),
            @ApiResponse(code = 119, message = "查询失败"),
            @ApiResponse(code = 120, message = "不存在订单"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @GetMapping(value = "/queryBillByMemberId/{memberId}")
    public ReturnResult queryBillByMemberId(@PathVariable("memberId") String memberId) {
        try {
            Bill bill = billService.selectBillByMemberId(Long.valueOf(memberId), System.currentTimeMillis());
            if (null != bill) {
                MemberBillVo memberBillVo = new MemberBillVo();
                BeanUtils.copyProperties(bill, memberBillVo);
                //创建时间
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                memberBillVo.setCreatedAt(bill.getCreatedAt());
                //商家名称
                Shop shop = shopService.selectShop(bill.getShopId());
                memberBillVo.setShopName(shop.getName());
                //更新支付状态为待支付
                bill.setState(3);
                billService.updateBillById(bill);
                return ReturnResultUtils.returnSuccess(memberBillVo);
            } else {
                return ReturnResultUtils.returnNoSuccessMsg(120, "不存在订单");
            }
        } catch (Exception e) {
            log.error("查询订单失败！" + e);
            return ReturnResultUtils.returnFailMsg(119, "查询失败！");
        }
    }

    @ApiOperation(value = "订单  删除接口")
    @ApiResponses({
            @ApiResponse(code = 118, message = "删除成功"),
            @ApiResponse(code = 119, message = "删除失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @DeleteMapping("/{id}")
    public ReturnResult deleteBillById(@PathVariable("id") Long id) {
        try {
            billService.deleteBillById(id);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("删除失败" + e);
            return ReturnResultUtils.returnFailMsg(119, "删除失败");
        }
    }

    @ApiOperation(value = "订单  修改接口")
    @ApiResponses({
            @ApiResponse(code = 120, message = "修改成功"),
            @ApiResponse(code = 121, message = "修改失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PutMapping("/{id}")
    public ReturnResult updateBillById(@RequestBody Bill bill) {
        try {
            billService.updateBillById(bill);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("修改失败" + e);
            return ReturnResultUtils.returnFailMsg(121, "修改失败");
        }
    }

    @ApiOperation(value = "订单  分页查询接口")
    @ApiResponses({
            @ApiResponse(code = 122, message = "查询成功"),
            @ApiResponse(code = 123, message = "查询失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @GetMapping
    public ReturnResult selectBillsPage(@RequestParam(defaultValue = "1", required = false) Integer page, @RequestParam(required = false, defaultValue = "20") Integer limit) {
        try {
            Map map = billService.selectBillsPage(page, limit);
            return ReturnResultUtils.returnSuccess(map);
        } catch (Exception e) {
            log.error("查询失败" + e);
            return ReturnResultUtils.returnFailMsg(123, "查询失败");
        }
    }

}
